*! version 1  19Nov2021 

capture program drop xtsum3
program define xtsum3, rclass /*byable(recall) sortpreserve*/
version 15.0
syntax  varlist(ts) [if] [in] , [ur] [check] [common] [re] [ml]


* opzioni: default is long with ts test

set more off

set linesize 255
*capture clear matrix
*capture clear mata
*capture set maxvar 32767


tokenize `varlist'

*if _by() {
*quietly replace `touse' = 0 if `_byindex' != _byindex()
*}  /* by */

*tempname ivar tvar
*g `ivar' = `r(panelvar)'
*g `tvar' = `r(timevar)'

*local ivar1 "`r(panelvar)'"
*local tvar1 "`r(timevar)'"

*** fundamental tsset/xtset before xtsum1
local ivar = r(panelvar)
local tvar = r(timevar)

if "`ivar'" == "" {
		di as err "You must tsset your panel (see tsset or xtset)"
		exit 498
	}

	local tvar "`r(timevar)'"

	if "`tvar'" == "" {
		di as err "You must tsset your panel (see tsset or xtset)"
		exit 498
	}

local step=r(tdelta)
* Tmin & Tmax specific number of time variable
local Tmin=r(tmin)
local TMAX = r(tmax)
local TTHEO = r(tmax)-r(tmin)+1
* error if I keep:
*local NTHEO = r(imax)
* because the N could be a not progressive code, so better
qui xtdes
local NTHEO = r(N) 
* Tmin and Tmax in terms of number 
local Tming = r(min)
local TMAXg = r(max)
local maxobs = `NTHEO'*`TTHEO'


qui summ 
* for dfgls test:

di in smcl in gr "{hline 33}" _col(35) in gr "Level 2 (i): " as result `"`ivar'"' _skip(3) in gr "Level 1 (j): " as result `"`tvar'"' _col(78) in gr "{hline 23}"
di in smcl                    _col(35) in gr "Hypothetical full sample, Ni x Nj: " as result `"`maxobs'"' 
di in smcl                    _col(35) in gr "Ni: " as result `"`NTHEO'"' _skip(3) in gr "Nj: " as result `"`TTHEO'"'  

di in smcl in gr  "{hline 33}{hline 25}{hline 16}{hline 26}" /*
*/ _n "Variable" _col(34) "{c |}" _skip(3) "Mean" _skip(3) "Std.Dev." _skip(2) "% SS" _skip(1) "{c |}" /*
*/ _skip(2) "Observations" _skip(2) "{c |}" _skip(2) "Test" /*
*/ _n "{hline 33}{c +}{hline 25}{c +}{hline 16}{c +}{hline 23}"  


* selection of the sample
if "`re'" == ""&"`ml'" == "" {
    foreach var of local varlist {
quietly {

marksample touse, novarlist

if "`common'" != "" {
marksample touse
    }

tempname TM_`var' TSD_`var'  TSS_`var' ///
BSSr2_`var' BSDr2_`var' BSSpr2_`var' ///
WSSfe2_`var' WSDfe2_`var' WSSpfe2_`var' ///
RSSfet21_`var' RSDfet21_`var'  RSSpfet21_`var' ///
BSSr1_`var' BSDr1_`var' BSSpr1_`var'   BSSppr1_`var' ///
BSSbe2_`var' BSDbe2_`var' BSSpbe2_`var'    ///
WSSrbe2_`var' WSDrbe2_`var' WSSprbe2_`var'    ///
BSSrbe1_`var' BSDrbe1_`var' BSSprbe1_`var' BSSpprbe1_`var'  ///
BSSwls2_`var' BSDwls2_`var' BSSpwls2_`var'   ///
WSSrwls2_`var' WSDrwls2_`var' WSSprwls2_`var'   ///
BSSrwls1_`var' BSDrwls1_`var' BSSprwls1_`var' BSSpprwls1_`var'   ///
BSSfe2_`var'  BSDfe2_`var' BSSpfe2_`var'   ///
WSSrfe2_`var' WSDrfe2_`var' WSSprfe2_`var'   ///
BSSrfe1_`var' BSDrfe1_`var' BSSprfe1_`var' BSSpprfe1_`var'    ///
BSSfet2_`var' BSDfet2_`var' BSSpfet2_`var'    ///
WSSrfet2_`var' WSDrfet2_`var' WSSprfet2_`var'   ///
BSSrfet1_`var' BSDrfet1_`var' BSSprfet1_`var' BSSpprfet1_`var'   ///
RSSpfet21c_`var'   ///
BSSbe1_`var' BSDbe1_`var' BSSpbe1_`var' BSSppbe1_`var' ///
BSSwls1_`var' BSDwls1_`var' BSSpwls1_`var'  BSSppwls1_`var'  ///
BSSfe1_`var' BSDfe1_`var' BSSpfe1_`var' BSSppfe1_`var'   ///
RSSrbe21_`var' RSDrbe21_`var'  RSSprbe21_`var' ///
RSSrwls21_`var' RSDrwls21_`var'  RSSprwls21_`var' ///
RSSrfe21_`var' RSDrfe21_`var'  RSSprfe21_`var' ///
NT_`var' N_`var' Nmax_`var' Nmin_`var' Nbar_`var' Tmax_`var' Tmin_`var' Tbar_`var' T_`var' ///
Fnum2_`var' Fden2_`var' F2_`var' Fpval2_`var' ///
Fnum1_`var' Fden1_`var' F1_`var' Fpval1_`var'  ///
deg_unb_`var' tau_`var' pval_`var' tau1_`var' pval1_`var' ///
BSSp2a_`var' BSSp2aa_`var' WSD2a_`var' BSSp1a_`var' BSSp1aa_`var' RSD21a_`var'


* total variability
xtsum `var' if `touse'  
scalar `TM_`var'' =r(mean)
scalar `TSD_`var'' =r(sd)

*
* inter_`ivar' variability check
xtreg `var' if `touse', be i(`ivar')
scalar `BSDbe2_`var'' =e(rmse)  
xtreg `var' if `touse', be wls i(`ivar')
scalar `BSDwls2_`var'' =e(rmse)
*
* Total intra_`ivar' variability & inter_`ivar' variability 
* in unbalanced panel it is not the same from either xtreg, fe i(i) or xtreg i.t, fe i(i)
xtreg `var' if `touse', fe i(`ivar')
scalar `WSDfe2_`var'' =e(sigma_e)
scalar `BSDfe2_`var'' =e(sigma_u)
scalar `NT_`var''  =e(N)
scalar `N_`var''   =e(N_g)
scalar `Tmax_`var'' =e(g_max)
scalar `Tmin_`var'' =e(g_min)
scalar `Tbar_`var'' =e(g_avg)
scalar `deg_unb_`var'' = `NT_`var''/(`maxobs')*100

* intra_`ivar'_`tvar' variability or crossed effects (two-ways model regression):
* maybe xi: areg `var' i.`tvar' if `touse', absorb(`ivar') is faster 
* (for sure it must absorb the most numerous factor)
* but it doesn't provide sigma_u which could be different from a model without i.t
* qui occorre introdurre il test UR su TD
xtreg `var' i.`tvar' if `touse', fe i(`ivar')
scalar `Fnum2_`var'' =e(df_a)
scalar `Fden2_`var'' =e(df_r)
scalar `F2_`var''    =e(F_f)
scalar `Fpval2_`var'' =Ftail(`Fnum2_`var'', `Fden2_`var'', `F2_`var'')
scalar `BSDfet2_`var''   =e(sigma_u)
scalar `RSDfet21_`var''   =e(sigma_e)
 
*testparm _I`tvar'*
testparm i.`tvar'
scalar `T_`var'' =r(df)+1
scalar `Fnum1_`var'' =r(df)
scalar `Fden1_`var'' =r(df_r)
scalar `F1_`var''    =r(F)
scalar `Fpval1_`var'' =Ftail(`Fnum1_`var'', `Fden1_`var'', `F1_`var'')
*drop  _I`tvar'*

if "`ur'" != "" {
 
 
	  

											  
 
* UR test on common factors
* unbalanced panel: counter should start from the first available
/*
summ `tvar' if `touse'&`var'!=.
local imax=r(max)
local i=r(min)+`step'
	di "inizio=" `i'
	
	g tempo_`var'=`i' if `tvar'==`i'
	g stima_`var'=_b[`i'.`tvar'] if `tvar'==`i'
	
while `i'<=`imax'  {
	 
	replace tempo_`var'=`i' if `tvar'==`i'
    replace stima_`var'=_b[`i'.`tvar'] if `tvar'==`i'
sort tempo_`var' 
di `i' " " tempo_`var' " " stima_`var'
*local ++i
local i=`i'+`step'
}
*/
*** il loop sopra genera problemi se non esiste qualche anno per qualche variabile (solo common mi salva)
* quindi meglio levelsof
* Occorre generare l'impresa becnhmark (più presente) subito
* poi il test seguirà l'esistenza o meno della stima

*** bilanciamento del panel per avere pickone corretto, ma deve essere fatto sul campione disponibile
summ `tvar' 
tempname dista1_`var'
local dista1_`var'=r(max)-r(min)+1
tempname maxyear
by `ivar': g `maxyear'=_N 

summ `tvar' if `touse'&e(sample)
tempname dista_`var'
local dista_`var'=r(max)-r(min)+1

local check_`var'=r(max)-r(min)

noisily if `Fnum1_`var''<`check_`var'' {
    di as error "Interruptions in the time series of some variables" ///
		   _n "Error codes r(2000) or r(498) (r(127))" ///
		   _n "Investigate your data and add an if option"
           *capture drop `prefix'*
		   *exit 198
	
}


tempname chiuso_`var'
if `maxyear'==`dista1_`var'' {
by `ivar': g byte `chiuso_`var'' =0 if _N>=`dista_`var''&`touse'
}
else if `maxyear'<`dista1_`var'' {
by `ivar': g byte `chiuso_`var'' =0 if _N==`dista_`var''&`touse'
}

summ `ivar' if  `chiuso_`var''==0

tempname pickone_`var'
g `pickone_`var''=`ivar'==r(min)

* adesso genero le stime in base a disponibilità dati var by var
tempname tempo_`var' 
 g `tempo_`var''=.
tempname stima_`var' 
 g `stima_`var''=.
		
levelsof `tvar' if `touse'&e(sample), local(after)
*local after "`r(levels)'"
	*foreach yr in `after' {
	foreach yr of local after {
		replace `tempo_`var''=`yr' if `tvar'==`yr'
		replace `stima_`var''=_b[`yr'.`tvar'] if `tvar'==`yr'
		}
****** ADESSO VERIFICO ANCHE LA MEDIA
tsset `ivar' `tvar'

tempname `var'_dotj
egen ``var'_dotj'=mean(`var') if `touse', by(`tvar')

	noisily if `Tbar_`var''<9 {
           di as error "The lenght of time series could be not enough to compute UR test" ///
		   _n "(also because of interruptions in the time series of some variables)" ///
		   _n "Error code r(127) (or r(2000) or r(498))" 
           *capture drop `prefix'*
		   *exit 198
		   }       

dfgls ``var'_dotj' if `pickone_`var''==1, /*maxlag(`aug')*/ notrend ers

 
local maic =  r(maiclag)

dfgls ``var'_dotj' if `pickone_`var''==1, maxlag(`maic') notrend ers

return list
matrix list r(results)
matrix mat_pippo=r(results)
*scalar maxlag =  r(maxlag)
*local tau=el(mat_pippo,maxlag,5)
local tau1_`var'=el(mat_pippo,1,5)

di `tau1_`var''
*
if `tau1_`var''>-1.04 {
#d ;
local min=-9999 ; /* "min" param. for tau>x case don't matter aslongas x>min */ 
local max=. ; 
local g0=0.4797 ; 
local g1=0.93557 ; 
local g2=-0.06999 ; 
local g3=0.033066 ;
#d cr
			}
	else {
#d ;
local min=-19.04 ;
local max=. ; 
local g0=0.6344 ; 
local g1=1.2378 ; 
local g2=0.032496 ;
local g3=0 ;
#d cr
			}
local h    = `g0' + `g1'*`tau1_`var'' + `g2'*(`tau1_`var'')^2 + `g3'*(`tau1_`var'')^3
local pval1_`var' = cond(`tau1_`var''<`min',0,cond(`tau1_`var''>`max',1,normprob(`h')))
di `pval1_`var''

****		
dfgls `stima_`var'' if `pickone_`var''==1, /*maxlag(`aug')*/ notrend ers
local maic =  r(maiclag)
			
dfgls `stima_`var'' if `pickone_`var''==1, maxlag(`maic') notrend ers
return list
matrix list r(results)
matrix mat_pippo=r(results)
*scalar maxlag =  r(maxlag)
*local tau=el(mat_pippo,maxlag,5)
local tau_`var'=el(mat_pippo,1,5)

di `tau_`var''
*
if `tau_`var''>-1.04 {
#d ;
local min=-9999 ; /* "min" param. for tau>x case don't matter aslongas x>min */ 
local max=. ; 
local g0=0.4797 ; 
local g1=0.93557 ; 
local g2=-0.06999 ; 
local g3=0.033066 ;
#d cr
			}
	else {
#d ;
local min=-19.04 ;
local max=. ; 
local g0=0.6344 ; 
local g1=1.2378 ; 
local g2=0.032496 ;
local g3=0 ;
#d cr
			}
local h    = `g0' + `g1'*`tau_`var'' + `g2'*(`tau_`var'')^2 + `g3'*(`tau_`var'')^3
local pval_`var' = cond(`tau_`var''<`min',0,cond(`tau_`var''>`max',1,normprob(`h')))
di `pval_`var''

													
tsline ``var'_dotj' `stima_`var'' if `pickone_`var''==1, legend(order(1 "Computed CF" 2 "Estimated CF")) title("`var'") saving(UR_`var'.gph, replace) nodraw

capture drop  _I`tvar'*

    }  /* UR */



tsset `ivar' `tvar'
	
	
* inter_`tvar' variability
xtreg `var' if `touse', be i(`tvar')
scalar `BSDbe1_`var'' =e(rmse)
xtreg `var' if `touse', be wls i(`tvar')
scalar `BSDwls1_`var'' =e(rmse)

xtreg `var' if `touse', fe i(`tvar')
scalar `BSDfe1_`var'' =e(sigma_u)
scalar `Nmax_`var'' =e(g_max)
scalar `Nmin_`var'' =e(g_min)
scalar `Nbar_`var'' =e(g_avg)

*** obtaining both SS and SD
scalar `TSS_`var''       = `TSD_`var''^2*(`NT_`var''-1)
scalar `WSSfe2_`var''    = `WSDfe2_`var''^2*(`NT_`var''-`N_`var'')
scalar `BSSr2_`var''     = `TSS_`var''-`WSSfe2_`var''
scalar `BSDr2_`var''     = (`BSSr2_`var''/(`NT_`var''-`Tbar_`var''))^0.5
scalar `RSSfet21_`var''  = `RSDfet21_`var''^2*(`NT_`var''-`N_`var''-`T_`var''+1)
scalar `BSSr1_`var''     = `TSS_`var''-`BSSr2_`var''-`RSSfet21_`var''
scalar `BSDr1_`var''     = (`BSSr1_`var''/(`NT_`var''-`Nbar_`var''))^0.5



*** calcolo % SS
* % between inter_`ivar' (xi.-x..)/(xit-x..) 
* Denominators equivalent to TSS
scalar `BSSpr2_`var''    = `BSSr2_`var''/(`BSSr2_`var''+`BSSr1_`var''+`RSSfet21_`var'')*100

* % between inter_`tvar' (x.t-x..)/(xit-x..)
scalar `BSSpr1_`var''    = `BSSr1_`var''/(`BSSr2_`var''+`BSSr1_`var''+`RSSfet21_`var'')*100

* % within  intra_`ivar'_`tvar' (xit-xi.-x.t+x..)/(xit-x..)
scalar `RSSpfet21_`var'' = `RSSfet21_`var''/(`BSSr2_`var''+`BSSr1_`var''+`RSSfet21_`var'')*100

* - Focus on One-way individuals: intra_`ivar'+inter_`ivar'
* % within intra_`ivar' (xit-xi.)/(xit-x..)
scalar `WSSpfe2_`var''   = `WSSfe2_`var''/(`BSSr2_`var''+`WSSfe2_`var'')*100
* of which explained by between inter_`tvar' (%) (x.t-x..)/(xit-xi.)
scalar `BSSppr1_`var'' = (`BSSr1_`var''/(`BSSr2_`var''+`BSSr1_`var''+`RSSfet21_`var''))/(`WSSfe2_`var''/(`BSSr2_`var''+`WSSfe2_`var''))*100

}  /* quietly */ 

* `N_`var'' coincides with `Nmax_`var'' & `T_`var'' coincides with `Tmax_`var''

if "`ur'" == "" {
    


di in smcl in gr abbrev("`var'",8)    ///
   _col(8) as text "  Overall xij-x.."  _col(34) "{c |}" as result %7.4g `TM_`var''  _col(42) as result %9.4g `TSD_`var'' ///
   _col(60) as text "{c |}"               _col(62) "NiNj"                              _col(69) as result %8.0f `NT_`var'' ///
   as text "{c |}"                        _col(79) "`ivar' effects:"                                      ///
_n _col(8) as text "1-Between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDr2_`var''  ///
   _col(49) %8.2f `BSSpr2_`var''          _col(60) as text "{c |}" _col(62) "Ni"      _col(69) as result %8.0f `N_`var'' ///
   as text "{c |}"   ///   
  _col(80) "F(" in ye `Fnum2_`var'' as text ", " in ye `Fden2_`var'' as text ")"     _col(93) "=" in ye %7.2f `F2_`var''  ///
_n _col(8) as text "2-Within xij-xi." _col(34) "{c |}"                           _col(42) as result %9.4g `WSDfe2_`var'' ///   
   _col(49) %8.2f `WSSpfe2_`var''         _col(60) as text "{c |}" _col(62) "Ni-bar" _col(69) as result %8.2f `Nbar_`var'' ///
   as text "{c |}"                        _col(84) as text "Prob > F"             _col(93) "=" as result %7.2f `Fpval2_`var''  ///
_n _col(8) as text "{hline 6} of which: {hline 6}"  _col(34) "{c |}"  _col(60) as text "{c |}" _col(62) "Ni-max" _col(69) as result %8.0f `Nmax_`var'' ///
   as text "{c |}"                        _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text " 2a-res xij-xi.-x.j+x.." _col(34) "{c |}"  _col(42) as result %9.4g `RSDfet21_`var'' ///
   _col(49) %8.2f `RSSpfet21_`var''      _col(60) "{c |}"    _col(62) "Nj"         _col(69) as result %8.0f `T_`var'' ///
   as text "{c |}"   ///
  _col(80) "F(" in ye `Fnum1_`var'' as text ", " in ye `Fden1_`var'' as text ")"     _col(93) "=" in ye %7.2f `F1_`var''  ///          
_n _col(8) as text " 2b-between x.j-x.." _col(34) "{c |}"  _col(42) as result %9.4g `BSDr1_`var'' ///
   _col(49) %8.2f `BSSpr1_`var''      _col(60) "{c |}"   _col(62) "Nj-bar" _col(69) as result %8.0f  `Tbar_`var'' ///
   as text "{c |}"                        _col(84) as text "Prob > F"              _col(93) "=" as result %7.2f `Fpval1_`var'' ///         
_n _col(9) as text " (2b in % of 2)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppr1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(62) "Nj-max" _col(69) as result %8.2f `Tmax_`var'' ///
   as text "{c |}"                        _col(79) as text "balancedness"     _col(93) "=" as result %7.2f `deg_unb_`var''    ///
_n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"  
 
} /* no ur */ 


if "`ur'" != "" {
	
	
	
di in smcl in gr abbrev("`var'",8)    ///
   _col(8) as text "  Overall xij-x.."  _col(34) "{c |}" as result %7.4g `TM_`var''  _col(42) as result %9.4g `TSD_`var'' ///
   _col(60) as text "{c |}"               _col(62) "NiNj"                              _col(69) as result %8.0f `NT_`var'' ///
   as text "{c |}"                        _col(79) "`ivar' effects:"                                      ///
_n _col(8) as text "1-Between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDr2_`var''  ///
   _col(49) %8.2f `BSSpr2_`var''          _col(60) as text "{c |}" _col(62) "Ni"      _col(69) as result %8.0f `N_`var'' ///
   as text "{c |}"   ///   
  _col(80) "F(" in ye `Fnum2_`var'' as text ", " in ye `Fden2_`var'' as text ")"     _col(93) "=" in ye %7.2f `F2_`var''  ///
_n _col(8) as text "2-Within xij-xi." _col(34) "{c |}"                           _col(42) as result %9.4g `WSDfe2_`var'' ///   
   _col(49) %8.2f `WSSpfe2_`var''         _col(60) as text "{c |}" _col(62) "Ni-bar" _col(69) as result %8.2f `Nbar_`var'' ///
   as text "{c |}"                        _col(84) as text "Prob > F"             _col(93) "=" as result %7.2f `Fpval2_`var''  ///
_n _col(8) as text "{hline 6} of which: {hline 6}"  _col(34) "{c |}"  _col(60) as text "{c |}" _col(62) "Ni-max" _col(69) as result %8.0f `Nmax_`var'' ///
   as text "{c |}"                        _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text " 2a-res xij-xi.-x.j+x.." _col(34) "{c |}"  _col(42) as result %9.4g `RSDfet21_`var'' ///
   _col(49) %8.2f `RSSpfet21_`var''      _col(60) "{c |}"    _col(62) "Nj"         _col(69) as result %8.0f `T_`var'' ///
   as text "{c |}"   ///
  _col(80) "F(" in ye `Fnum1_`var'' as text ", " in ye `Fden1_`var'' as text ")"     _col(93) "=" in ye %7.2f `F1_`var''  ///          
_n _col(8) as text " 2b-between x.j-x.. (CF)" _col(34) "{c |}"  _col(42) as result %9.4g `BSDr1_`var'' ///
   _col(49) %8.2f `BSSpr1_`var''      _col(60) "{c |}"   _col(62) "Nj-bar" _col(69) as result %8.0f  `Tbar_`var'' ///
   as text "{c |}"                        _col(84) as text "Prob > F"              _col(93) "=" as result %7.2f `Fpval1_`var'' ///         
_n _col(9) as text " (2b in % of 2)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppr1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(62) "Nj-max" _col(69) as result %8.2f `Tmax_`var'' ///
   as text "{c |}"                        _col(79) as text "balancedness"     _col(93) "=" as result %7.2f `deg_unb_`var''    ///
_n  _col(9) as text " Estimated CF x.j" _col(34) "{c |}"       _col(60) as text "{c |}"                                             _col(77) as text "{c |}" ///
                                             _col(79) as text "H0: UR - pval"    _col(93) "=" as result %7.2f `pval_`var''    ///
_n  _col(9) as text " Computed  CF x.j" _col(34) "{c |}"       _col(60) as text "{c |}"                                             _col(77) as text "{c |}" ///
                                             _col(79) as text "H0: UR - pval"    _col(93) "=" as result %7.2f `pval1_`var''    ///
_n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"  
 
} /* yes ur */

 
 
 
 
 * Saving some results for the last variable of the varlist: 
ret scalar TM_`var'  = `TM_`var''
ret scalar TSS_`var' = `TSS_`var'' 
ret scalar TSD_`var' = `TSD_`var'' 
ret scalar BSSr2_`var'  = `BSSr2_`var''
ret scalar BSDr2_`var'  = `BSDr2_`var''
ret scalar BSSpr2_`var'  = `BSSpr2_`var''
ret scalar BSSr1_`var'  = `BSSr1_`var''
ret scalar BSDr1_`var'  = `BSDr1_`var''
ret scalar BSSpr1_`var'  = `BSSpr1_`var''
ret scalar BSSppr1_`var'  = `BSSppr1_`var''
ret scalar WSSfe2_`var'  = `WSSfe2_`var''
ret scalar WSDfe2_`var'  = `WSDfe2_`var''
ret scalar WSSpfe2_`var'  = `WSSpfe2_`var''
ret scalar RSSfet21_`var'  = `RSSfet21_`var''
ret scalar RSDfet21_`var'  = `RSDfet21_`var''
ret scalar RSSpfet21_`var'  = `RSSpfet21_`var''
ret scalar deg_unb_`var' = `deg_unb_`var''
ret scalar NT_`var' = `NT_`var''
ret scalar N_`var' = `N_`var''
ret scalar T_`var' = `T_`var''
ret scalar Nbar_`var' = `Nbar_`var''
ret scalar Tbar_`var' = `Tbar_`var''
ret scalar Fpval2_`var' = `Fpval2_`var''
ret scalar Fpval1_`var' = `Fpval1_`var''
*ret scalar UR_`var' = `deg_unb_`var''

***************** metti definizione tabella da esporto 
* dopo che ho eseguito xtsum3 x1 x2 posso dare:
*(it is based on the community-contributed command esttab (type ssc install estout to download) for exporting the produced (LaTeX) table)
*esttab e(mat_xtsum3), mlabels(none) labcol2(`e(comp)') varlabels(r2 " " r3 " ")
*esttab e(mat_xtsum3), mlabels(none) labcol2(`e(comp)') varlabels(r2 " " r3 " ") tex


/*
***  export table
 tempname mat_`var'
    matrix mat_`var' = J(5, 5, .)
    matrix mat_`var'[1,1] = (`r(TM_`var')', `r(TSD_`var')', ., `r(NT_`var')', .)
    matrix mat_`var'[2,1] = (., `r(BSDr2_`var')', `r(BSDpr2_`var')', `r(N_`var')', `r(Fpval2_`var')')
    matrix mat_`var'[3,1] = (., `r(BSDr1_`var')', `r(BSDpr1_`var')', `r(T_`var')', `r(Fpval1_`var')')
	matrix mat_`var'[4,1] = (., `r(RSDfet21_`var')', `r(RSDpfet21_`var')', `r(Nbar_`var')', `r(deg_unb_`var')')
    matrix mat_`var'[5,1] = (., `r(WSDfe2_`var')', `r(WSDpfe2_`var')', `r(Tbar_`var')', .)
	matrix colnames mat_`var'= Mean "Std. Dev." "% SS" "Obs." Tests
    matrix rownames mat_`var'= `var' " " " " " " " "

    local matall `matall' mat_`var'
    local comp `comp' overall between(i) between(j) residual within(i)

if `= wordcount("`varlist'")' > 1 {
    local matall = subinstr("`matall'", " ", " \ ",.)
    matrix allmat = (`matall')
    *ereturn matrix mat_xtsum3 = allmat
    return matrix mat_xtsum3 = allmat
	}
*else ereturn matrix mat_all = mat_`varlist'
*ereturn local comp = "`comp'"
else return matrix mat_all = mat_`varlist'
return local comp = "`comp'"

********************************
CHE PALLE: MI DA 
, not found
r(111);

E NON CAPISCO PERCHE'
*********************************
*/


********************

} /* each var */
 
foreach var of local varlist { 
if "`check'" != "" {
qui {	

tsset `ivar' `tvar'

*BSSp2 is the R2 in
areg `var', absorb(`ivar')
scalar `BSSp2a_`var''   = e(r2)*100
scalar `BSSp2aa_`var''  = e(r2_a)*100
* while the rmse is WSD2
scalar `WSD2a_`var'' = e(rmse) 

*BSSp1 is the R2 in
areg `var', absorb(`tvar')
scalar `BSSp1a_`var''    = e(r2)*100
scalar `BSSp1aa_`var''   = e(r2_a)*100
* while the rmse is BSD2+(WSD2-BSD1)

*RSDfet21 is the rmse in
areg `var' i.`tvar', absorb(`ivar')
scalar `RSD21a_`var'' = e(rmse) 
* the R2 is TSS-BSS2-BSS1=RSS+(WSS-BSS1)
*scalar `RSSpfet21c_`var''    = 100-e(r2)*100
*scalar `RSSpfet21ca_`var''   = 100-e(r2_a)*100


scalar `BSSbe2_`var''   = `BSDbe2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `BSSpbe2_`var''  = `BSSbe2_`var''/(`TSS_`var'')*100
scalar `BSSrbe1_`var''  = `TSS_`var''-`BSSbe2_`var''-`RSSfet21_`var''
scalar `BSDrbe1_`var''  = (`BSSrbe1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `BSSprbe1_`var'' = `BSSrbe1_`var''/(`TSS_`var'')*100
scalar `WSSrbe2_`var''  = `TSS_`var''-`BSSbe2_`var''
scalar `WSDrbe2_`var''  = (`WSSrbe2_`var''/(`NT_`var''-`N_`var''))^0.5
scalar `WSSprbe2_`var'' = `WSSrbe2_`var''/(`TSS_`var'')*100
scalar `BSSpprbe1_`var'' = (`BSSrbe1_`var''/(`BSSbe2_`var''+`BSSrbe1_`var''+`RSSfet21_`var''))/(`WSSrbe2_`var''/(`BSSbe2_`var''+`WSSrbe2_`var''))*100

scalar `RSSpfet21c_`var'' = `RSSfet21_`var''/(`TSS_`var'')*100


scalar `BSSwls2_`var''  = `BSDwls2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `BSSpwls2_`var'' = `BSSwls2_`var''/(`TSS_`var'')*100

scalar `BSSrwls1_`var'' = `TSS_`var''-`BSSwls2_`var''-`RSSfet21_`var''
scalar `BSDrwls1_`var'' = (`BSSrwls1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `BSSprwls1_`var'' = `BSSrwls1_`var''/(`TSS_`var'')*100
scalar `WSSrwls2_`var'' = `TSS_`var''-`BSSwls2_`var''
scalar `WSDrwls2_`var'' = (`WSSrwls2_`var''/(`NT_`var''-`N_`var''))^0.5
scalar `WSSprwls2_`var'' = `WSSrwls2_`var''/(`TSS_`var'')*100
scalar `BSSpprwls1_`var'' = (`BSSrwls1_`var''/(`BSSwls2_`var''+`BSSrwls1_`var''+`RSSfet21_`var''))/(`WSSrwls2_`var''/(`BSSwls2_`var''+`WSSrwls2_`var''))*100

scalar `BSSfe2_`var''   = `BSDfe2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `BSSpfe2_`var''   = `BSSfe2_`var''/(`TSS_`var'')*100
scalar `BSSrfe1_`var''  = `TSS_`var''-`BSSfe2_`var''-`RSSfet21_`var''
scalar `BSDrfe1_`var''  = (`BSSrfe1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `BSSprfe1_`var''  = `BSSrfe1_`var''/(`TSS_`var'')*100

scalar `WSSrfe2_`var''  = `TSS_`var''-`BSSfe2_`var''
scalar `WSDrfe2_`var''  = (`WSSrfe2_`var''/(`NT_`var''-`N_`var''))^0.5
scalar `WSSprfe2_`var''  = `WSSrfe2_`var''/(`TSS_`var'')*100
scalar `BSSpprfe1_`var'' = (`BSSrfe1_`var''/(`BSSfe2_`var''+`BSSrfe1_`var''+`RSSfet21_`var''))/(`WSSrfe2_`var''/(`BSSfe2_`var''+`WSSrfe2_`var''))*100

scalar `BSSfet2_`var''  = `BSDfet2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `BSSpfet2_`var''  = `BSSfet2_`var''/(`TSS_`var'')*100
scalar `BSSrfet1_`var'' = `TSS_`var''-`BSSfet2_`var''-`RSSfet21_`var''
scalar `BSDrfet1_`var'' = (`BSSrfet1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `BSSprfet1_`var'' = `BSSrfet1_`var''/(`TSS_`var'')*100

scalar `WSSrfet2_`var'' = `TSS_`var''-`BSSfet2_`var''
scalar `WSDrfet2_`var'' = (`WSSrfet2_`var''/(`NT_`var''-`N_`var''))^0.5
scalar `WSSprfet2_`var'' = `WSSrfet2_`var''/(`TSS_`var'')*100
scalar `BSSpprfet1_`var'' = (`BSSrfet1_`var''/(`BSSfet2_`var''+`BSSrfet1_`var''+`RSSfet21_`var''))/(`WSSrfet2_`var''/(`BSSfet2_`var''+`WSSrfet2_`var''))*100

* both i and j between
scalar `BSSbe1_`var''     = `BSDbe1_`var''^2*(`NT_`var''-`Nbar_`var'')
scalar `BSSpbe1_`var''    = `BSSbe1_`var''/(`TSS_`var'')*100

scalar `RSSrbe21_`var''   = `TSS_`var''-`BSSbe2_`var''-`BSSbe1_`var''
scalar `RSDrbe21_`var''   = (`RSSrbe21_`var''/(`NT_`var''-`T_`var''-`N_`var''))^0.5
scalar `RSSprbe21_`var''  = `RSSrbe21_`var''/(`TSS_`var'')*100

scalar `WSSrbe2_`var''  = `TSS_`var''-`BSSbe2_`var''

*scalar `WSSrbe2_`var''  = `TSS_`var''-`BSSbe2_`var''

scalar `BSSppbe1_`var'' = (`BSSbe1_`var''/(`BSSbe2_`var''+`BSSbe1_`var''+`RSSrbe21_`var''))/(`WSSrbe2_`var''/(`BSSbe2_`var''+`WSSrbe2_`var''))*100

scalar `BSSwls1_`var''    = `BSDwls1_`var''^2*(`NT_`var''-`Nbar_`var'')
scalar `BSSpwls1_`var''   = `BSSwls1_`var''/(`TSS_`var'')*100

scalar `RSSrwls21_`var''  = `TSS_`var''-`BSSwls2_`var''-`BSSwls1_`var''
scalar `RSDrwls21_`var''  = (`RSSrwls21_`var''/(`NT_`var''-`T_`var''-`N_`var''))^0.5
scalar `RSSprwls21_`var'' = `RSSrwls21_`var''/(`TSS_`var'')*100

scalar `BSSppwls1_`var''  = (`BSSwls1_`var''/(`BSSwls2_`var''+`BSSwls1_`var''+`RSSrwls21_`var''))/(`WSSrwls2_`var''/(`BSSwls2_`var''+`WSSrwls2_`var''))*100

scalar `BSSfe1_`var''     = `BSDfe1_`var''^2*(`NT_`var''-`Nbar_`var'')
scalar `BSSpfe1_`var''   = `BSSfe1_`var''/(`TSS_`var'')*100
scalar `RSSrfe21_`var''   = `TSS_`var''-`BSSfe2_`var''-`BSSfe1_`var''
scalar `RSDrfe21_`var''   = (`RSSrfe21_`var''/(`NT_`var''-`T_`var''-`N_`var''))^0.5

scalar `RSSprfe21_`var'' = `RSSrfe21_`var''/(`TSS_`var'')*100
scalar `BSSppfe1_`var''  = (`BSSfe1_`var''/(`BSSfe2_`var''+`BSSfe1_`var''+`RSSrfe21_`var''))/(`WSSrfe2_`var''/(`BSSfe2_`var''+`WSSrfe2_`var''))*100

} /* qui */


di
di in smcl in gr "{hline 33}" _col(35) as input "Other computations" in gr " - Variable: " "`var'"  _col(78) in gr "{hline 23}"
di "{hline 100}"
di            _col(69) as input "Std.Dev." _col(80) as input "in % of TSS"  
di "{hline 100}"
*di as input "Over TSS"                                                                
di as text "between xi.-x.. (from xtreg, be i(i))"      _col(64) "="  _col(66) as result %9.4g `BSDbe2_`var''                                                        _col(80) as result  %4.2f `BSSpbe2_`var''                ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDrbe1_`var''                                                        _col(80) as result  %4.2f `BSSprbe1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."   					_col(64) "="  _col(66) as result %9.4g `RSDfet21_`var''                                                        _col(80) as result  %4.2f `RSSpfet21c_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrbe2_`var''                                                        _col(80) as result  %4.2f `WSSprbe2_`var''    													_col(95) as result "(" %4.2f `BSSpprbe1_`var'' ")" ///
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg, be i(i) wls)"  _col(64) "="  _col(66) as result %9.4g `BSDwls2_`var''                                                        _col(80) as result  %4.2f `BSSpwls2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDrwls1_`var''                                                        _col(80) as result  %4.2f `BSSprwls1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDfet21_`var''                                                        _col(80) as result  %4.2f `RSSpfet21c_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrwls2_`var''                                                        _col(80) as result  %4.2f `WSSprwls2_`var''       												  _col(95) as result "(" %4.2f `BSSpprwls1_`var'' ")" ///
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg, fe i(i))"      _col(64) "="  _col(66) as result %9.4g `BSDfe2_`var''                                                        _col(80) as result  %4.2f `BSSpfe2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDrfe1_`var''                                                        _col(80) as result  %4.2f `BSSprfe1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDfet21_`var''                                                        _col(80) as result  %4.2f `RSSpfet21c_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrfe2_`var''                                                        _col(80) as result  %4.2f `WSSprfe2_`var''     													_col(95) as result "(" %4.2f `BSSpprfe1_`var'' ")"   ///
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg i.j, fe i(i))"  _col(64) "="  _col(66) as result %9.4g `BSDfet2_`var''                                                        _col(80) as result  %4.2f `BSSpfet2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDrfet1_`var''                                                        _col(80) as result  %4.2f `BSSprfet1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDfet21_`var''                                                        _col(80) as result  %4.2f `RSSpfet21c_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrfet2_`var''                                                        _col(80) as result  %4.2f `WSSprfet2_`var'' 														  _col(95) as result "(" %4.2f `BSSpprfet1_`var'' ")"   ///
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg, be i(j))"      _col(64) "="  _col(66) as result %9.4g `BSDbe2_`var''                                                        _col(80) as result  %4.2f `BSSpbe2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDbe1_`var''                                                        _col(80) as result  %4.2f `BSSpbe1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDrbe21_`var''                                                        _col(80) as result  %4.2f `RSSprbe21_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrbe2_`var''                                                        _col(80) as result  %4.2f `WSSprbe2_`var''  														_col(95) as result "(" %4.2f `BSSppbe1_`var'' ")"   ///  
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg, be i(j) wls)"  _col(64) "="  _col(66) as result %9.4g `BSDwls2_`var''                                                        _col(80) as result  %4.2f `BSSpwls2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDwls1_`var''                                                        _col(80) as result  %4.2f `BSSpwls1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDrwls21_`var''                                                        _col(80) as result  %4.2f `RSSprwls21_`var''     ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrwls2_`var''                                                        _col(80) as result  %4.2f `WSSprwls2_`var'' 														  _col(95) as result "(" %4.2f `BSSppwls1_`var'' ")"  ///
_n "{hline 100}" ///
_n as text "between xi.-x.. (from xtreg, fe i(j))"      _col(64) "="  _col(66) as result %9.4g `BSDfe2_`var''                                                        _col(80) as result  %4.2f `BSSpfe2_`var''              ///
_n as text "between x.j-x.."							_col(64) "="  _col(66) as result %9.4g `BSDfe1_`var''                                                        _col(80) as result  %4.2f `BSSpfe1_`var''                  ///
_n as text "resid xij-xi.-x.j+x.."						_col(64) "="  _col(66) as result %9.4g `RSDrfe21_`var''                                                        _col(80) as result  %4.2f `RSSprfe21_`var''    ///
_n as text "within xij-xi."								_col(64) "="  _col(66) as result %9.4g `WSDrfe2_`var''                                                        _col(80) as result  %4.2f `WSSprfe2_`var'' 														 _col(95) as result "(" %4.2f `BSSppfe1_`var'' ")"
di

}  /* check */
} /* each var */
} /* RE=""*/


************
****************
*******************
if "`re'" != ""&"`ml'" == "" {
foreach var of local varlist {
quietly {

marksample touse, novarlist

if "`common'" != "" {
marksample touse
    }

tempname TM_`var' TSD_`var'  TSS_`var' ///
BSSre2_`var' BSDre2_`var' BSSpre2_`var' ///
WSSre2_`var' WSDre2_`var' WSSpre2_`var' ///
RSSrer21_`var' RSDrer21_`var'  RSSprer21_`var' ///
BSSre1_`var' BSDre1_`var' BSSpre1_`var'   BSSppre1_`var' ///
BSSret2_`var' BSDret2_`var' BSSpret2_`var' ///
RSSret21_`var' RSDret21_`var'  RSSpret21_`var' ///
BSSret1_`var' BSDret1_`var' BSSpret1_`var'   BSSppret1_`var' ///
WSSret2_`var' WSDret2_`var' WSSpret2_`var' ///
NT_`var' N_`var' Nmax_`var' Nmin_`var' Nbar_`var' Tmax_`var' Tmin_`var' Tbar_`var' T_`var' ///
chi2num2_`var' chi22_`var' chi2pval2_`var' ///
chi2num1_`var' chi21_`var' chi2pval1_`var' ///
chi2num2t_`var' chi22t_`var' chi2pval2t_`var' ///
chi2num1t_`var' chi21t_`var' chi2pval1t_`var' ///
deg_unb_`var'  

* total variability
xtsum `var' if `touse'  
scalar `TM_`var'' =r(mean)
scalar `TSD_`var'' =r(sd)

* Total intra_`ivar' variability & inter_`ivar' variability 
* in unbalanced panel it is not the same from either xtreg, fe i(i) or xtreg i.t, fe i(i)
xtreg `var' if `touse', re i(`ivar')
scalar `WSDre2_`var'' =e(sigma_e)
scalar `BSDre2_`var'' =e(sigma_u)
scalar `NT_`var''  =e(N)
scalar `N_`var''   =e(N_g)
scalar `Tmax_`var'' =e(g_max)
scalar `Tmin_`var'' =e(g_min)
scalar `Tbar_`var'' =e(g_avg)
scalar `deg_unb_`var'' = `NT_`var''/(`maxobs')*100

xttest0
scalar `chi2num2_`var'' =r(df)
scalar `chi22_`var''    =r(lm)
scalar `chi2pval2_`var'' =r(p)

xtreg `var' if `touse', re i(`tvar')
scalar `BSDre1_`var'' =e(sigma_u)
scalar `Nmax_`var'' =e(g_max)
scalar `Nmin_`var'' =e(g_min)
scalar `Nbar_`var'' =e(g_avg)

xttest0
scalar `chi2num1_`var'' =r(df)
scalar `chi21_`var''    =r(lm)
scalar `chi2pval1_`var'' =r(p)

* another possibility is to consider j as deterministic:
* no base category: xtreg `var' ibn.`tvar' if `touse', re i(`ivar')
xtreg `var' i.`tvar' if `touse', re i(`ivar')
scalar `RSDret21_`var'' =e(sigma_e)
scalar `BSDret2_`var''  =e(sigma_u)

testparm i.`tvar'
scalar `T_`var'' =r(df)+1
scalar `chi2num1t_`var'' =r(df)
scalar `chi21t_`var''    =r(chi2)
scalar `chi2pval1t_`var'' =r(p)

xttest0
scalar `chi2num2t_`var'' =r(df)
scalar `chi22t_`var''    =r(lm)
scalar `chi2pval2t_`var'' =r(p)

*** obtaining both SS and SD
scalar `TSS_`var''       = `TSD_`var''^2*(`NT_`var''-1)
scalar `WSSre2_`var''    = `WSDre2_`var''^2*(`NT_`var''-`N_`var'')
scalar `BSSre2_`var''    = `TSS_`var''-`WSSre2_`var''
scalar `BSDre2_`var''    = (`BSSre2_`var''/(`NT_`var''-`Tbar_`var''))^0.5
scalar `BSSre1_`var''    = `BSDre1_`var''^2*(`NT_`var''-`Nbar_`var'')
scalar `RSSrer21_`var''  = `TSS_`var''-`BSSre2_`var''-`BSSre1_`var''
scalar `RSDrer21_`var''  = (`RSSrer21_`var''/(`NT_`var''-`N_`var''-`T_`var''+1))^0.5
*

scalar `BSSret2_`var''   = `BSDret2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `RSSret21_`var''  = `RSDret21_`var''^2*(`NT_`var''-`N_`var''-`T_`var''+1)
scalar `BSSret1_`var''   = `TSS_`var''-`BSSret2_`var''-`RSSret21_`var''
scalar `BSDret1_`var''   = (`BSSret1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `WSSret2_`var''   = `BSSret1_`var''+`RSSret21_`var''
scalar `WSDret2_`var''   = (`WSSret2_`var''/(`NT_`var''-`N_`var''))^0.5

*** calcolo % SS
* % between inter_`ivar' (xi.-x..)/(xij-x..) 
* Denominators equivalent to TSS
scalar `BSSpre2_`var''    = `BSSre2_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* % between inter_`tvar' (x.j-x..)/(xij-x..)
scalar `BSSpre1_`var''    = `BSSre1_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* % within  intra_`ivar'_`tvar' (xij-xi.-x.j+x..)/(xij-x..)
scalar `RSSprer21_`var'' = `RSSrer21_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* - Focus on One-way individuals: intra_`ivar'+inter_`ivar'
* % within intra_`ivar' (xij-xi.)/(xij-x..)
scalar `WSSpre2_`var''   = `WSSre2_`var''/(`BSSre2_`var''+`WSSre2_`var'')*100
* of which explained by between inter_`tvar' (%) (x.j-x..)/(xij-xi.)
scalar `BSSppre1_`var'' = (`BSSre1_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var''))/(`WSSre2_`var''/(`BSSre2_`var''+`WSSre2_`var''))*100

* The other way:
scalar `BSSpret2_`var'' = (`BSSret2_`var''/`TSS_`var'')*100
* equivalent to
*scalar `BSSpret2_`var'' = (`BSSret2_`var''/(`BSSret2_`var''+`BSSret1_`var''+`RSSret21_`var''))*100
scalar `BSSpret1_`var''  = (`BSSret1_`var''/`TSS_`var'')*100
scalar `RSSpret21_`var''  = (`RSSret21_`var''/`TSS_`var'')*100
scalar `WSSpret2_`var''  = (`WSSret2_`var''/`TSS_`var'')*100
scalar `BSSppret1_`var'' = (`BSSret1_`var''/(`BSSret2_`var''+`BSSret1_`var''+`RSSret21_`var''))/(`WSSret2_`var''/(`BSSret2_`var''+`WSSret2_`var''))*100

	
}  /* quietly */ 

* `N_`var'' coincides with `Nmax_`var'' & `T_`var'' coincides with `Tmax_`var''

di in smcl in gr abbrev("`var'",8)    ///
   _col(8) as text "    overall xij-x.."  _col(34) "{c |}" as result %7.4g `TM_`var''  _col(42) as result %9.4g `TSD_`var'' ///
   _col(60) as text "{c |}"               _col(62) "NiNj"                              _col(69) as result %8.0f `NT_`var'' ///
   as text "{c |}"                        _col(79) "`ivar' effects:"                                      ///
_n _col(8) as text "(1) between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDre2_`var''  ///
   _col(49) %8.2f `BSSpre2_`var''          _col(60) as text "{c |}" _col(62) "Ni"      _col(69) as result %8.0f `N_`var'' ///
   as text "{c |}"   ///   
  _col(80) "Chi2(" in ye `chi2num2_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi22_`var''  ///
_n _col(8) as text "(2a) between x.j-x.." _col(34) "{c |}"                           _col(42) as result %9.4g `BSDre1_`var'' ///   
   _col(49) %8.2f `BSSpre1_`var''          _col(60) as text "{c |}" _col(62) "Ni-bar" _col(69) as result %8.2f `Nbar_`var'' ///
   as text "{c |}"                        _col(81) as text "Prob > Chi2"             _col(93) "=" as result %7.2f `chi2pval2_`var''  ///
_n _col(8) as text "(2b) res xij-xi.-x.j+x.." _col(34) "{c |}"                    _col(42) as result %9.4g `RSDrer21_`var'' ///
   _col(49) %8.2f `RSSprer21_`var''           _col(60) "{c |}"     _col(62) "Ni-max" _col(69) as result %8.0f `Nmax_`var'' ///
   as text "{c |}"                        _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text "{hline 6} (2a) + (2b): {hline 6}"                                     ///
                                          _col(34) "{c |}"         _col(44) "{hline 16}"     ///
                                          _col(60) "{c |}"         _col(62) "Nj"    _col(69) as result %8.0f `T_`var'' ///
   as text "{c |}"   ///
  _col(80) "Chi2(" in ye `chi2num1_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi21_`var''  ///
_n _col(8) as text "(2)  within xij-xi."  _col(34) "{c |}"                          _col(42) as result %9.4g `WSDre2_`var'' ///   
   _col(49) %8.2f `WSSpre2_`var''         _col(60) as text "{c |}" _col(62) "Nj-bar" _col(69) as result %8.0f  `Tbar_`var'' ///
   as text "{c |}"                        _col(81) as text "Prob > Chi2"              _col(93) "=" as result %7.2f `chi2pval1_`var'' ///
_n _col(9) as text "(% (2a) between x.j-x..)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppre1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(62) "Nj-max" _col(69) as result %8.2f `Tmax_`var'' ///
   as text "{c |}"                        _col(79) as text "balancedness"     _col(93) "=" as result %7.2f `deg_unb_`var''    ///
_n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"   ///
_n _col(8) as text "j deterministic:" _col(34) "{c |}" _col(60) as text "{c |}" _col(77) as text "{c |}" _col(79) "`ivar' effects:" ///
_n _col(8) as text "(3) between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDret2_`var''  ///
   _col(49) %8.2f `BSSpret2_`var''          _col(60) as text "{c |}" _col(77) as text "{c |}"   ///   
  _col(80) "Chi2(" in ye `chi2num2t_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi22t_`var''  ///
_n _col(8) as text "(4a) between x.j-x.." _col(34) "{c |}"                           _col(42) as result %9.4g `BSDret1_`var'' ///   
   _col(49) %8.2f `BSSpret1_`var''          _col(60) as text "{c |}" _col(77) as text "{c |}"  _col(81) as text "Prob > Chi2"             _col(93) "=" as result %7.2f `chi2pval2t_`var''  ///
_n _col(8) as text "(4b) res xij-xi.-x.j+x.." _col(34) "{c |}"                    _col(42) as result %9.4g `RSDret21_`var'' ///
   _col(49) %8.2f `RSSpret21_`var''           _col(60) "{c |}"     _col(77)  as text "{c |}"    _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text "{hline 5} (4a) + (4b): {hline 5}"                                     ///
                                          _col(34) "{c |}"         _col(44) "{hline 16}"     ///
                                          _col(60) "{c |}"         _col(77)  as text "{c |}"   ///
  _col(80) "Chi2(" in ye `chi2num1t_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi21t_`var''  ///
_n _col(8) as text "(4)  within xij-xi."  _col(34) "{c |}"                          _col(42) as result %9.4g `WSDret2_`var'' ///   
   _col(49) %8.2f `WSSpret2_`var''         _col(60) as text "{c |}" _col(77) as text "{c |}"  _col(81) as text "Prob > Chi2"              _col(93) "=" as result %7.2f `chi2pval1t_`var'' ///
_n _col(9) as text "(% (4a) between x.j-x..)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppret1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(77) as text "{c |}"    ///
 _n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"  

 
* Saving some results for the last variable of the varlist: 
ret scalar TM_`var'  = `TM_`var''
ret scalar TSS_`var' = `TSS_`var'' 
ret scalar TSD_`var' = `TSD_`var'' 
ret scalar BSSre2_`var'  = `BSSre2_`var''
ret scalar BSDre2_`var'  = `BSDre2_`var''
ret scalar BSSpre2_`var'  = `BSSpre2_`var''
ret scalar BSSre1_`var'  = `BSSre1_`var''
ret scalar BSDre1_`var'  = `BSDre1_`var''
ret scalar BSSpre1_`var'  = `BSSpre1_`var''
ret scalar BSSppre1_`var'  = `BSSppre1_`var''
ret scalar WSSre2_`var'  = `WSSre2_`var''
ret scalar WSDre2_`var'  = `WSDre2_`var''
ret scalar WSSpre2_`var'  = `WSSpre2_`var''
ret scalar RSSrer21_`var'  = `RSSrer21_`var''
ret scalar RSDrer21_`var'  = `RSDrer21_`var''
ret scalar RSSprer21_`var'  = `RSSprer21_`var''
ret scalar deg_unb_`var' = `deg_unb_`var''
ret scalar NT_`var' = `NT_`var''
ret scalar N_`var' = `N_`var''
ret scalar T_`var' = `T_`var''
ret scalar Nbar_`var' = `Nbar_`var''
ret scalar Tbar_`var' = `Tbar_`var''
ret scalar chi2pval2_`var' = `chi2pval2_`var''
ret scalar chi2pval1_`var' = `chi2pval1_`var''
*ret scalar UR_`var' = `deg_unb_`var''

***************** metti definizione tabella da esporto 

} /* each var */
 
} /* RE!="" */

**************


if "`re'" == ""&"`ml'" != "" {
foreach var of local varlist {
quietly {

marksample touse, novarlist

if "`common'" != "" {
marksample touse
    }

tempname TM_`var' TSD_`var'  TSS_`var' ///
BSSre2_`var' BSDre2_`var' BSSpre2_`var' ///
WSSre2_`var' WSDre2_`var' WSSpre2_`var' ///
RSSrer21_`var' RSDrer21_`var'  RSSprer21_`var' ///
BSSre1_`var' BSDre1_`var' BSSpre1_`var'   BSSppre1_`var' ///
BSSret2_`var' BSDret2_`var' BSSpret2_`var' ///
RSSret21_`var' RSDret21_`var'  RSSpret21_`var' ///
BSSret1_`var' BSDret1_`var' BSSpret1_`var'   BSSppret1_`var' ///
WSSret2_`var' WSDret2_`var' WSSpret2_`var' ///
NT_`var' N_`var' Nmax_`var' Nmin_`var' Nbar_`var' Tmax_`var' Tmin_`var' Tbar_`var' T_`var' ///
chi2num2_`var' chi22_`var' chi2pval2_`var' ///
chi2num1_`var' chi21_`var' chi2pval1_`var' ///
chi2num2t_`var' chi22t_`var' chi2pval2t_`var' ///
chi2num1t_`var' chi21t_`var' chi2pval1t_`var' ///
deg_unb_`var'  

* total variability
xtsum `var' if `touse'  
scalar `TM_`var'' =r(mean)
scalar `TSD_`var'' =r(sd)

* Total intra_`ivar' variability & inter_`ivar' variability 
* in unbalanced panel it is not the same from either xtreg, fe i(i) or xtreg i.t, fe i(i)
* The same as mixed `var' if `touse' || `ivar': , stddev but faster: 
xtreg `var' if `touse', re i(`ivar')
scalar `WSDre2_`var'' =e(sigma_e)
scalar `BSDre2_`var'' =e(sigma_u)
scalar `NT_`var''  =e(N)
scalar `N_`var''   =e(N_g)
scalar `Tmax_`var'' =e(g_max)
scalar `Tmin_`var'' =e(g_min)
scalar `Tbar_`var'' =e(g_avg)
scalar `deg_unb_`var'' = `NT_`var''/(`maxobs')*100

xttest0
scalar `chi2num2_`var'' =r(df)
scalar `chi22_`var''    =r(lm)
scalar `chi2pval2_`var'' =r(p)

xtreg `var' if `touse', re i(`tvar')
scalar `BSDre1_`var'' =e(sigma_u)
scalar `Nmax_`var'' =e(g_max)
scalar `Nmin_`var'' =e(g_min)
scalar `Nbar_`var'' =e(g_avg)

xttest0
scalar `chi2num1_`var'' =r(df)
scalar `chi21_`var''    =r(lm)
scalar `chi2pval1_`var'' =r(p)

* another possibility is to consider j as deterministic:
xtreg `var' i.`tvar' if `touse', re i(`ivar')
scalar `RSDret21_`var'' =e(sigma_e)
scalar `BSDret2_`var''  =e(sigma_u)

testparm i.`tvar'
scalar `T_`var'' =r(df)+1
scalar `chi2num1t_`var'' =r(df)
scalar `chi21t_`var''    =r(chi2)
scalar `chi2pval1t_`var'' =r(p)

xttest0
scalar `chi2num2t_`var'' =r(df)
scalar `chi22t_`var''    =r(lm)
scalar `chi2pval2t_`var'' =r(p)

*** obtaining both SS and SD
scalar `TSS_`var''       = `TSD_`var''^2*(`NT_`var''-1)
scalar `WSSre2_`var''    = `WSDre2_`var''^2*(`NT_`var''-`N_`var'')
scalar `BSSre2_`var''    = `TSS_`var''-`WSSre2_`var''
scalar `BSDre2_`var''    = (`BSSre2_`var''/(`NT_`var''-`Tbar_`var''))^0.5
scalar `BSSre1_`var''    = `BSDre1_`var''^2*(`NT_`var''-`Nbar_`var'')
scalar `RSSrer21_`var''  = `TSS_`var''-`BSSre2_`var''-`BSSre1_`var''
scalar `RSDrer21_`var''  = (`RSSrer21_`var''/(`NT_`var''-`N_`var''-`T_`var''+1))^0.5
*

scalar `BSSret2_`var''   = `BSDret2_`var''^2*(`NT_`var''-`Tbar_`var'')
scalar `RSSret21_`var''  = `RSDret21_`var''^2*(`NT_`var''-`N_`var''-`T_`var''+1)
scalar `BSSret1_`var''   = `TSS_`var''-`BSSret2_`var''-`RSSret21_`var''
scalar `BSDret1_`var''   = (`BSSret1_`var''/(`NT_`var''-`Nbar_`var''))^0.5
scalar `WSSret2_`var''   = `BSSret1_`var''+`RSSret21_`var''
scalar `WSDret2_`var''   = (`WSSret2_`var''/(`NT_`var''-`N_`var''))^0.5

*** calcolo % SS
* % between inter_`ivar' (xi.-x..)/(xij-x..) 
* Denominators equivalent to TSS
scalar `BSSpre2_`var''    = `BSSre2_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* % between inter_`tvar' (x.j-x..)/(xij-x..)
scalar `BSSpre1_`var''    = `BSSre1_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* % within  intra_`ivar'_`tvar' (xij-xi.-x.j+x..)/(xij-x..)
scalar `RSSprer21_`var'' = `RSSrer21_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var'')*100
* - Focus on One-way individuals: intra_`ivar'+inter_`ivar'
* % within intra_`ivar' (xij-xi.)/(xij-x..)
scalar `WSSpre2_`var''   = `WSSre2_`var''/(`BSSre2_`var''+`WSSre2_`var'')*100
* of which explained by between inter_`tvar' (%) (x.j-x..)/(xij-xi.)
scalar `BSSppre1_`var'' = (`BSSre1_`var''/(`BSSre2_`var''+`BSSre1_`var''+`RSSrer21_`var''))/(`WSSre2_`var''/(`BSSre2_`var''+`WSSre2_`var''))*100

* The other way:
scalar `BSSpret2_`var'' = (`BSSret2_`var''/`TSS_`var'')*100
* equivalent to
*scalar `BSSpret2_`var'' = (`BSSret2_`var''/(`BSSret2_`var''+`BSSret1_`var''+`RSSret21_`var''))*100
scalar `BSSpret1_`var''  = (`BSSret1_`var''/`TSS_`var'')*100
scalar `RSSpret21_`var''  = (`RSSret21_`var''/`TSS_`var'')*100
scalar `WSSpret2_`var''  = (`WSSret2_`var''/`TSS_`var'')*100
scalar `BSSppret1_`var'' = (`BSSret1_`var''/(`BSSret2_`var''+`BSSret1_`var''+`RSSret21_`var''))/(`WSSret2_`var''/(`BSSret2_`var''+`WSSret2_`var''))*100

	
}  /* quietly */ 

* `N_`var'' coincides with `Nmax_`var'' & `T_`var'' coincides with `Tmax_`var''

di in smcl in gr abbrev("`var'",8)    ///
   _col(8) as text "    overall xij-x.."  _col(34) "{c |}" as result %7.4g `TM_`var''  _col(42) as result %9.4g `TSD_`var'' ///
   _col(60) as text "{c |}"               _col(62) "NiNj"                              _col(69) as result %8.0f `NT_`var'' ///
   as text "{c |}"                        _col(79) "`ivar' effects:"                                      ///
_n _col(8) as text "(1) between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDre2_`var''  ///
   _col(49) %8.2f `BSSpre2_`var''          _col(60) as text "{c |}" _col(62) "Ni"      _col(69) as result %8.0f `N_`var'' ///
   as text "{c |}"   ///   
  _col(80) "Chi2(" in ye `chi2num2_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi22_`var''  ///
_n _col(8) as text "(2a) between x.j-x.." _col(34) "{c |}"                           _col(42) as result %9.4g `BSDre1_`var'' ///   
   _col(49) %8.2f `BSSpre1_`var''          _col(60) as text "{c |}" _col(62) "Ni-bar" _col(69) as result %8.2f `Nbar_`var'' ///
   as text "{c |}"                        _col(81) as text "Prob > Chi2"             _col(93) "=" as result %7.2f `chi2pval2_`var''  ///
_n _col(8) as text "(2b) res xij-xi.-x.j+x.." _col(34) "{c |}"                    _col(42) as result %9.4g `RSDrer21_`var'' ///
   _col(49) %8.2f `RSSprer21_`var''           _col(60) "{c |}"     _col(62) "Ni-max" _col(69) as result %8.0f `Nmax_`var'' ///
   as text "{c |}"                        _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text "{hline 6} (2a) + (2b): {hline 6}"                                     ///
                                          _col(34) "{c |}"         _col(44) "{hline 16}"     ///
                                          _col(60) "{c |}"         _col(62) "Nj"    _col(69) as result %8.0f `T_`var'' ///
   as text "{c |}"   ///
  _col(80) "Chi2(" in ye `chi2num1_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi21_`var''  ///
_n _col(8) as text "(2)  within xij-xi."  _col(34) "{c |}"                          _col(42) as result %9.4g `WSDre2_`var'' ///   
   _col(49) %8.2f `WSSpre2_`var''         _col(60) as text "{c |}" _col(62) "Nj-bar" _col(69) as result %8.0f  `Tbar_`var'' ///
   as text "{c |}"                        _col(81) as text "Prob > Chi2"              _col(93) "=" as result %7.2f `chi2pval1_`var'' ///
_n _col(9) as text "(% (2a) between x.j-x..)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppre1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(62) "Nj-max" _col(69) as result %8.2f `Tmax_`var'' ///
   as text "{c |}"                        _col(79) as text "balancedness"     _col(93) "=" as result %7.2f `deg_unb_`var''    ///
_n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"   ///
_n _col(8) as text "(3) between xi.-x.."  _col(34) "{c |}"                            _col(42) as result %9.4g `BSDret2_`var''  ///
   _col(49) %8.2f `BSSpret2_`var''          _col(60) as text "{c |}" _col(77) as text "{c |}"   ///   
  _col(80) "Chi2(" in ye `chi2num2t_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi22t_`var''  ///
_n _col(8) as text "(4a) between x.j-x.." _col(34) "{c |}"                           _col(42) as result %9.4g `BSDret1_`var'' ///   
   _col(49) %8.2f `BSSpret1_`var''          _col(60) as text "{c |}" _col(77) as text "{c |}"  _col(81) as text "Prob > Chi2"             _col(93) "=" as result %7.2f `chi2pval2t_`var''  ///
_n _col(8) as text "(4b) res xij-xi.-x.j+x.." _col(34) "{c |}"                    _col(42) as result %9.4g `RSDret21_`var'' ///
   _col(49) %8.2f `RSSpret21_`var''           _col(60) "{c |}"     _col(77)  as text "{c |}"    _col(79) "`tvar' effects:"                   ///                           
_n _col(8) as text "{hline 5} (IIa) + (IIb): {hline 5}"                                     ///
                                          _col(34) "{c |}"         _col(44) "{hline 16}"     ///
                                          _col(60) "{c |}"         _col(77)  as text "{c |}"   ///
  _col(80) "Chi2(" in ye `chi2num1t_`var'' as text ")"     _col(93) "=" in ye %7.2f `chi21t_`var''  ///
_n _col(8) as text "(4)  within xij-xi."  _col(34) "{c |}"                          _col(42) as result %9.4g `WSDret2_`var'' ///   
   _col(49) %8.2f `WSSpret2_`var''         _col(60) as text "{c |}" _col(77) as text "{c |}"  _col(81) as text "Prob > Chi2"              _col(93) "=" as result %7.2f `chi2pval1t_`var'' ///
_n _col(9) as text "(% (4a) between x.j-x..)" _col(34) "{c |}"     _col(53) as result "(" %4.2f `BSSppret1_`var'' ")"    ///
   _col(60) as text "{c |}"                                        _col(77) as text "{c |}"    ///
 _n "{hline 33}{c BT}{hline 25}{c BT}{hline 16}{c BT}{hline 23}"  

 
* Saving some results for the last variable of the varlist: 
ret scalar TM_`var'  = `TM_`var''
ret scalar TSS_`var' = `TSS_`var'' 
ret scalar TSD_`var' = `TSD_`var'' 
ret scalar BSSre2_`var'  = `BSSre2_`var''
ret scalar BSDre2_`var'  = `BSDre2_`var''
ret scalar BSSpre2_`var'  = `BSSpre2_`var''
ret scalar BSSre1_`var'  = `BSSre1_`var''
ret scalar BSDre1_`var'  = `BSDre1_`var''
ret scalar BSSpre1_`var'  = `BSSpre1_`var''
ret scalar BSSppre1_`var'  = `BSSppre1_`var''
ret scalar WSSre2_`var'  = `WSSre2_`var''
ret scalar WSDre2_`var'  = `WSDre2_`var''
ret scalar WSSpre2_`var'  = `WSSpre2_`var''
ret scalar RSSrer21_`var'  = `RSSrer21_`var''
ret scalar RSDrer21_`var'  = `RSDrer21_`var''
ret scalar RSSprer21_`var'  = `RSSprer21_`var''
ret scalar deg_unb_`var' = `deg_unb_`var''
ret scalar NT_`var' = `NT_`var''
ret scalar N_`var' = `N_`var''
ret scalar T_`var' = `T_`var''
ret scalar Nbar_`var' = `Nbar_`var''
ret scalar Tbar_`var' = `Tbar_`var''
ret scalar chi2pval2_`var' = `chi2pval2_`var''
ret scalar chi2pval1_`var' = `chi2pval1_`var''
*ret scalar UR_`var' = `deg_unb_`var''

***************** metti definizione tabella da esporto 

} /* each var */
 
} /* ML!="" */




/*
foreach var of local varlist {
if "`ml'" != "" {


												
									   
							 
													  

BSSml2_`var' BSDml2_`var'  BSSpml2_`var' 
WSSml2_`var' WSDml2_`var' WSSpml2_`var'
RSSmlt21_`var' RSDmlt21_`var'
BSSml1_`var' BSDml1_`var' BSSpml1_`var' BSSppml1_`var'

BSSreml2_`var' BSDreml2_`var' BSSpreml2_`var' ///
WSSreml2_`var' WSDreml2_`var' WSSpreml2_`var' ///
RSSremlt21_`var' RSDremlt21_`var' ///
BSSreml1_`var' BSDreml1_`var'  BSSpreml1_`var' BSSppreml1_`var' ///

xtreg `var' if `touse', re i(`ivar')
scalar `WSDre2_`var'' =e(sigma_e)
scalar `BSDre2_`var'' =e(sigma_u)
* The same as mixed `var' if `touse' || `ivar': , stddev but faster: 
xtreg `var' if `touse', mle i(`ivar')
scalar `WSDml2_`var'' =e(sigma_e)
scalar `BSDml2_`var'' =e(sigma_u)
mixed `var' if `touse' || `ivar': , stddev reml
scalar `WSDreml2_`var'' =exp([lnsig_e]_cons)
scalar `BSDreml2_`var'' =exp([lns1_1_1]_cons)
*display exp(2*[lns1_1_1]_cons)/(exp(2*[lns1_1_1]_cons)  + exp(2*[lnsig_e]_cons))
*display exp(2*[lnsig_e]_cons)/(exp(2*[lns1_1_1]_cons)  + exp(2*[lnsig_e]_cons))

xtreg `var' if `touse', re i(`tvar')
scalar `BSDre1_`var'' =e(sigma_u)
xtreg `var' if `touse', mle i(`tvar')
scalar `BSDml1_`var'' =e(sigma_u)
mixed `var' if `touse' || `tvar': , stddev reml
*scalar `WSDreml1_`var'' =exp([lnsig_e]_cons)
scalar `BSDreml1_`var'' =exp([lns1_1_1]_cons)

*xtreg `var' i.`tvar' if `touse', re i(`ivar')
*scalar `RSDret21_`var''   =e(rmse)


xtmixed var_Interesse || var_categoriale:,mle

estimates store nome

xtmixed var_interesse, mle

lrtest ri .

scalar test=r(p)/2


mixed tint ||_all:R.codice || anno:, stddev
display exp(2*[lns1_1_1]_cons)/(exp(2*[lns1_1_1]_cons) + exp(2*[lns2_1_1]_cons) ///
 + exp(2*[lnsig_e]_cons))
display exp(2*[lns2_1_1]_cons)/(exp(2*[lns1_1_1]_cons) + exp(2*[lns2_1_1]_cons) ///
 + exp(2*[lnsig_e]_cons))
display exp(2*[lnsig_e]_cons)/(exp(2*[lns1_1_1]_cons) + exp(2*[lns2_1_1]_cons) ///
 + exp(2*[lnsig_e]_cons))
capture noisily matrix list r(Co


*
* Begin here
*
estimates store Both

// Variance component for cohort5
quietly mixed tint || anno:
lrtest Both .
display in smcl as text r(p) / 2

// Variance component for year
mixed tint `predictors' || _all:R.codice
lrtest Both .
display in smcl as text r(p) / 2



*
*** calcolo % SS for details
* total den
scalar `BSSpret2_`var'' = (`BSDre2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`TSS_`var''))*100
scalar `BSSpmlt2_`var'' = (`BSDml2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`TSS_`var''))*100
scalar `BSSpremlt2_`var'' = (`BSDreml2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`TSS_`var''))*100

* Residual den
scalar `BSSpre2_`var'' = (`BSDre2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSSr2_`var''+`BSSr1_`var''+`RSS21_`var''))*100
scalar `BSSpml2_`var'' = (`BSDml2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSSr2_`var''+`BSSr1_`var''+`RSS21_`var''))*100
scalar `BSSpreml2_`var'' = (`BSDreml2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSSr2_`var''+`BSSr1_`var''+`RSS21_`var''))*100

* their own den
scalar `BSSps_2_`var'' = (`BSD_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSD_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSD_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSwlsps_2_`var'' = (`BSDwls_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDwls_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSD_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSfeps_2_`var'' = (`BSDfe_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDfe_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSD_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSreps_2_`var'' = (`BSDre_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDre_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSDre_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSmlps_2_`var'' = (`BSDml_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDml_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSDml_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSmips_2_`var'' = (`BSDmi_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDmi_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSDmi_2_`var''^2*(`NT_`var''-`N_`var'')))*100
scalar `BSSmireps_2_`var'' = (`BSDmire_2_`var''^2*(`NT_`var''-`Tbar_`var'')/(`BSDmire_2_`var''^2*(`NT_`var''-`Tbar_`var'')+`WSDmire_2_`var''^2*(`NT_`var''-`N_`var'')))*100

scalar `BSSp_1_`var'' = (`BSD_1_`var''^2*(`NT_`var''-`Nbar_`var'')/(`BSSr_2_`var''+`BSSr_1_`var''+`RSS_2_1_`var''))*100
scalar `BSSwlsp_1_`var'' = (`BSDwls_1_`var''^2*(`NT_`var''-`Nbar_`var'')/(`BSSr_2_`var''+`BSSr_1_`var''+`RSS_2_1_`var''))*100
scalar `BSSfep_1_`var'' = (`BSDfe_1_`var''^2*(`NT_`var''-`Nbar_`var'')/(`BSSr_2_`var''+`BSSr_1_`var''+`RSS_2_1_`var''))*100
scalar `WSSp_1_`var'' = (`WSD_1_`var''^2*(`NT_`var''-`T_`var'')/(`BSSr_1_`var''+`WSSr_1_`var''))*100



di as input "Over TSS"  
_n as text "Between xi.-x.. (from xtreg, re i(i))"      _col(64) "="  _col(66) as result %9.5g `BSDre_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSrep_2_`var''              ///
_n as text "Between xi.-x.. (from xtreg, mle i(i))"     _col(64) "="  _col(66) as result %9.5g `BSDml_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmlp_2_`var''              ///
_n as text "Between xi.-x.. (from mixed || i )"         _col(64) "="  _col(66) as result %9.5g `BSDmi_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmip_2_`var''              ///
_n as text "Between xi.-x.. (from mixed || i, reml)"    _col(64) "="  _col(66) as result %9.5g `BSDmire_2_`var''  ///
    _col(80) as result  %4.2f `BSSmirep_2_`var''        
	
	
	
	di as input "Over TSS"       															  
di       as text "Between xi.-x.. (from xtreg, be i(i))"      _col(64) "="  _col(66) as result %9.5g `BSD_2_`var''    ///
                                                              _col(80) as result  %4.2f `BSSpt_2_`var''                ///
_newline as text "Between xi.-x.. (from xtreg, be i(i) wls)"  _col(64) "="  _col(66) as result %9.5g `BSDwls_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSwlspt_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, fe i(i))"      _col(64) "="  _col(66) as result %9.5g `BSDfe_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSfept_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, re i(i))"      _col(64) "="  _col(66) as result %9.5g `BSDre_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSrept_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, mle i(i))"     _col(64) "="  _col(66) as result %9.5g `BSDml_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmlpt_2_`var''              ///
_newline as text "Between xi.-x.. (from mixed || i )"         _col(64) "="  _col(66) as result %9.5g `BSDmi_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmipt_2_`var''              ///
_newline as text "Between xi.-x.. (from mixed || i, reml)"    _col(64) "="  _col(66) as result %9.5g `BSDmire_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmirept_2_`var''          
di as input "Over its own"       
di       as text "Between xi.-x.. (from xtreg, be i(i))"      _col(64) "="  _col(66) as result %9.5g `BSD_2_`var''    ///
                                                              _col(80) as result  %4.2f `BSSps_2_`var''                ///
_newline as text "Between xi.-x.. (from xtreg, be i(i) wls)"  _col(64) "="  _col(66) as result %9.5g `BSDwls_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSwlsps_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, fe i(i))"      _col(64) "="  _col(66) as result %9.5g `BSDfe_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSfeps_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, re i(i))"      _col(64) "="  _col(66) as result %9.5g `BSDre_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSreps_2_`var''              ///
_newline as text "Between xi.-x.. (from xtreg, mle i(i))"     _col(64) "="  _col(66) as result %9.5g `BSDml_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmlps_2_`var''              ///
_newline as text "Between xi.-x.. (from mixed || i )"         _col(64) "="  _col(66) as result %9.5g `BSDmi_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmips_2_`var''              ///
_newline as text "Between xi.-x.. (from mixed || i, reml)"    _col(64) "="  _col(66) as result %9.5g `BSDmire_2_`var''  ///
                                                              _col(80) as result  %4.2f `BSSmireps_2_`var''
di as input "Over summ of residuals"       
di       as text "Between x.t-x.. (from xtreg, be i(t))"      _col(64) "="   _col(66) as result %9.5g `BSD_1_`var''       ///
                                                              _col(80) as result  %4.2f `BSSp_1_`var''               ///
_newline as text "Between x.t-x.. (from xtreg, be i(t) wls)"  _col(64) "="   _col(66) as result %9.5g `BSDwls_1_`var''    ///
                                                              _col(80) as result  %4.2f `BSSwlsp_1_`var''                 ///
_newline as text "Between x.t-x.. (from xtreg, fe i(t))"      _col(64) "="   _col(66) as result %9.5g `BSDfe_1_`var''    ///
                                                              _col(80) as result  %4.2f `BSSfep_1_`var''             ///
_newline as text "Within  xit-x.t (from xtreg, fe i(t))"      _col(64) "="   _col(66) as result %9.5g `WSD_1_`var''   ///
                                                              _col(80) as result  %4.2f `WSSp_1_`var''             ///
_newline as text "areg two ways "							  _col(64) "="   _col(66) as result %9.5g `sigma_u2_`var''   ///




* Saving some results for the last variable of the varlist: 
ret scalar TM_`var'  = `TM_`var''
ret scalar TSS_`var' = `TSS_`var'' 
ret scalar TSD_`var' = `TSD_`var'' 
ret scalar BSSr_i_`var'  = `BSSr2_`var''
ret scalar BSDr_i_`var'  = `BSDr2_`var''
ret scalar BSSpr_i_`var'  = `BSSpr2_`var''
ret scalar BSSppr_i_`var'  = `BSSppr2_`var''
ret scalar BSSr_t_`var'  = `BSSr1_`var''
ret scalar BSDr_t_`var'  = `BSDr1_`var''
ret scalar BSSpr_t_`var'  = `BSSpr1_`var''
ret scalar BSSppr_t_`var'  = `BSSppr1_`var''
ret scalar WSS_i_`var'  = `WSSfe2_`var''
ret scalar WSD_i_`var'  = `WSDfe2_`var''
ret scalar WSSp_i_`var'  = `WSSpfe2_`var''
ret scalar RSS_it_`var'  = `RSSfet21_`var''
ret scalar RSD_it_`var'  = `RSDfet21_`var''
ret scalar RSSp_it_`var'  = `RSSpfet21_`var''
ret scalar deg_unb_`var' = `deg_unb_`var''

*ret scalar WSSr_t_`var'  = `WSSr_1_`var''
*ret scalar WSDr_t_`var'  = `WSDr_1_`var''
*ret scalar WSSpr_t_`var'  = `WSSpr_1_`var''
	
} /* re */	
}   /* for each var */

*/


end

**************************************
* COMMAND: xtsum19 list-of-variables
* It is necessary to type tsset or xtset i t before using the command.
* It can be used with if conditions

/*
The command is at the preliminary stage of the empirical analysis on panel data.
It tests the significance of individual and temporal effects (the options re and ml deal with multilevel panel, based on ML estimates);
it gives the variability (standard deviation) due:
- to individuals (CS or level 2, between units), 
- to time (TS or level 1, between time periods), 
- and residual (once we have taken into consideration individual and temporal heterogeneity, within or intra individuals-time periods)
The three components are comparatively evaluated in terms of percentages (using the sum of squares). 
The between time variability is a first proxy for the common factor driving all the units: the procedure also tests for the unit root in this common factor --> particularly useful for CSTS data (macro panels) 

Technical notes:

TSS_`var'=BSSi+WSSi=BSSt+WSSt=BSSi+(BSSt+WSSit)=BSSt+(BSSi+WSSit)
TSS_`var' is certain, with df (NT-1)
WSSi  WSSt and WSSit are certain, with df (NT-N) (NT-T) (NT-N-T+1), respectively,
where N and T indicate the total number of individual/temporal means.
Moreover, WSSit is the same from both xtreg, fe i(i) three-ways and xtreg, fe i(t) three-ways (individual and time effects allowed for).

Given the usual large number of individuals in longitudinal panels , it very time-expensive to compute individuals dummies and to run xtreg, fe i(t) three-ways. 
An trick could be to run xtreg y_WD, fe i(t), where _WD, within deviation, are able to take into account for individuals. However, the number of df is uncorrect and thus we should correct it. --> better the areg..., absorb(i)

While in balanced panels the alternatives give same results, in unbalanced panels we have problems for BSS because df are (NT-Tavg) and (NT-Navg).
xtreg, be wls is the preferred since it takes into account for heteroskedasticity due to different time periods for each individual. 
It is possible to obtain BSSi and BSSt by difference

The checks compare xtreg, be (equal to xtsum and xtreg, fe one-way), xtreg, be wls
In unbalanced panel xtreg, fe three-ways gives a different result 
*/

/*
UR on time dummies

prima devo generare una nuova variabile pari ai coeff stimati
xtreg tint i.anno, fe i(codice)
(equivale a stimare il modello FE con tau1981-tau1998)

Problema:
voglio generare nel dataset una variabile (che sarà pura time series)
uguale al vettore delle stime degli effetti temporali.
io sono arrivata a
matrix b=e(b)
matrix list b
ereturn post b
ereturn display
ok la vedo
ma come faccio a salvare questa serie storica (va bene anche ripetuta per ogni individuo)

Poi posso selezionare una sola TS con 
egen pickone=tag(anno)
sort anno
tab anno pickone
preserve
drop if pickone!=1
tsset anno
dfuller tint
restore
tab anno
 e questo FUNZIA!
 
H0: there is a UR!
 
 FE no inference for population of clusters but the minimum number of clusters required is any number
 RE inference for population of clusters but the minimum number of clusters required is at least 10/20
 NO UR you do not need to have a minimum cluster size 
 UR requires at least 15 observations for level 1
 
 RE requires level 2 exogeneity (Mundlak approach) and constant variance
 RE is more efficient than FE
 RE requires minimum cluster size >=2
 
 for two level random intercept models

*/